class RegistrationController < ApplicationController
  layout 'main'
  after_filter :post_log

  def index
    current_time= Time.now.utc
    @course_name = ''
    if params[:course_name]
      @course_name = params[:course_name]
    end
    if !@course_name.empty?
      syllabuses = Syllabus.find(:all, :conditions=>["name LIKE ? OR description LIKE ?", "%#{params[:course_name]}%", "%#{params[:course_name]}%"])
      if syllabuses.size>0
        @openings = SyllabusOpening.find :all, :conditions=>['open_flag=? and start<=? and end>=? and syllabus_id in (?)','Y',current_time,current_time, syllabuses.map{|s| s.id}]
      else
        @openings = SyllabusOpening.find :all, :conditions=>['open_flag=? and start<=? and end>=? and syllabus_id in (0)','Y',current_time,current_time]
      end
    else
      @openings = SyllabusOpening.find :all, :conditions=>['open_flag=? and start<=? and end>=?','Y',current_time,current_time]
    end
  end
  def register
    @opening = SyllabusOpening.find params[:id]
    @courses = SyllabusCourseMapper.find_all_by_syllabus_id(@opening.syllabus.id).collect {|m| m.course}
  end
  def create_register
    opening = SyllabusOpening.find params[:opening][:id]
    registration = Registration.new
    registration.syllabus_opening = opening
    registration.user = current_user
    registration.save
    courses = params[:course_ids]
    if courses
      courses.each do |item|
        registration_course = RegistrationCourse.new
        registration_course.registration = registration
        registration_course.course = Course.find item
        registration_course.save
      end
    end
    flash[:notice] = 'ลงทะเบียนเป็นที่เรียบร้อยแล้ว'
    redirect_to :action => 'index'
  end
  
end
